//
//  HLNetworking.m
//  weibo-OC
//
//  Created by 黄力 on 15/12/21.
//  Copyright © 2015年 HLTest. All rights reserved.
//

#import "HLNetworking.h"
#import <SVProgressHUD.h>

@implementation HLNetworking

//声明一个静态变量
static HLNetworking * _instance;

+ (instancetype)sharedNetworing {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[HLNetworking alloc] initWithBaseURL:[NSURL URLWithString:@"https://api.weibo.com/"]];
        //添加可解析的类型
        _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    });
    return _instance;
}

//普通的get和post请求
- (void)sendHTTPRequestWithHTTPMethod:(NSString *)HTTPMethod withUrlStr:(NSString *)urlStr withParameters:parameters withFinshedBlock: (FinshedBlock) finshedBlock {
    //任务默认是挂起的,要使用resume来执行
    //发送请求
    [[self dataTaskWithHTTPMethod:HTTPMethod URLString:urlStr parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        //成功的回调
        finshedBlock(responseObject, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
        //失败的回调
        finshedBlock(nil, error);
    }] resume];
}

//上传图片的post请求
- (void)uploadImageDataWithUrlStr:(NSString *)urlStr withParameters:(id)parameters withImageData:(NSData *)imageData withFinshBlock:(FinshedBlock) finshedBlock {
    [self POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"pic" fileName:@"123" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            CGFloat p = uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
            [SVProgressHUD showProgress:p];
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        finshedBlock(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finshedBlock(nil,error);
    }];
}

@end
